<?php
/**
 * 后台管理Controller
 * User: lvshuyun
 * Date: 2015/6/10
 * Time: 9:33
 */

namespace backend\controllers;

use common\models\DAO\AdminLog;
use common\models\DAO\AdminLogSearch;
use yii;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use backend\commands\BaseAdminController;
use common\models\DAO\Admin;
use common\models\DAO\AdminRole;
use common\models\Validate;


class AdminController extends BaseAdminController {

    //主页兼列表页
    public function actionList()
    {
        $Model = new Admin();
        $dataProvider = new ActiveDataProvider([
            'query' => $Model->find(),
            'pagination' => [
                'pageSize' => 20,
            ]
        ]);
        return $this->render(
            'list',
            [
                'model' => $Model,
                'dataProvider' => $dataProvider,
            ]
        );
    }

    /**
     * 添加
     */
    public function actionAdd()
    {
        $model = (new Admin(['scenario' => 'add']));
        if ($model->load(Yii::$app->request->post())) {
            if($model->save()){
                return $this->renderMessage('添加成功!', 'admin/list', 'success');
            }else{
                return $this->renderMessage('添加失败!', 'admin/list', 'danger', implode(',', $model->getErrors()));
            }
        }else{
            return $this->render('add', ['model'=>$model, 'roles'=>$this->getRolesArray()]);
        }
    }

    /*
     * 超级管理员角色修改
     */
    public function actionEdit($id)
    {
        $model = Admin::findOne($id);
        $model->setScenario('edit');
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if($model->save()){
                return $this->renderMessage('修改成功！', 'admin/list', 'success');
            }
            return $this->renderMessage('修改失败！', 'admin/list', 'danger');
        }else{
            return $this->render('edit', ['model'=>$model, 'roles'=>$this->getRolesArray()]);
        }
    }

    /*
     * 修改自己的资料
     */
    public function actionChangeProfile(){
        $id = Yii::$app->session->get('ADMIN_ID');
        if(!empty($id)){
            $Model = Admin::findOne($id);
            $Model->scenario = 'changeProfile';
            if($Model->load(Yii::$app->request->post()) && $Model->save()){
                return $this->renderMessage('修改成功', 'index/index', 'success');
            }else{
                return $this->render('change-profile', ['model'=>$Model]);
            }
        }else{
            return $this->renderMessage('你没有权限更改此管理员的资料', -1, 'danger');
        }
    }

    /*
     * 修改自己的密码
     */
    public function actionChangePassword(){
        $id = Yii::$app->session->get('ADMIN_ID');
        if(!empty($id)){
            $request = Yii::$app->request;
            $Model = Admin::findOne($id);
            $Model->scenario = 'changePassword';
            if($request->isPost){
                $pass = $request->post('Admin');
                if($Model->validatePassword($pass['oldPass'])){
                    $Model->adminPass = $pass['adminPass'];
                    if($Model->save()){
                        return $this->renderMessage('密码修改成功', 'index/index', 'success');
                    }else{
                        return $this->renderMessage('密码修改失败', -1, 'danger');
                    }
                }else{
                    return $this->renderMessage('原密码输入错误', -1, 'danger');
                }
            }else{
                return $this->render('change-password', ['model'=>$Model]);
            }
        }else{
            return $this->renderMessage('ID错误!', -1, 'danger');
        }
    }

    /*
     * 查看
     */
    public function actionView($id)
    {
        $Admin = new Admin(['scenario' => 'view']);
        $model = $Admin::find()->with('adminRole')->where(['id'=>$id])->one();
        if($model){
            return $this->render('view', ['model'=>$model]);
        }
        return $this->renderMessage('ID错误', '-1', 'danger');
    }

    /*
     * 删除
     */
    public function actionDelete($id = 0)
    {
        if(!empty($id)){
            $admin = Admin::findOne($id);
            if($admin->roleID >1){ //超级管理员禁止删除
                if($admin->delete()){
                    return $this->renderMessage('删除成功！', 'admin/list', 'success');
                }else{
                    return $this->renderMessage('删除失败！', 'admin/list', 'danger');
                }
            }else{
                return $this->renderAlert('此管理员禁止删除！', -1, 'danger');
            }
        }
        return $this->renderAlert('参数错误！', -1, 'danger');
    }

    /**
     * 管理员日志记录
     */
    public function actionAdminLog(){
        $Model = new AdminLog();
        $searchModel = new AdminLogSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->get());
        return $this->render(
            'list-log',
            [
                'model' => $Model,
                'searchModel' =>$searchModel,
                'dataProvider' => $dataProvider,
            ]
        );
    }

    /*
     * ActiveForm验证
     */
    public function actionAjaxValidate()
    {
        return $this->ajaxValidate(new Admin());
    }

    /*
     * 获得角色数组
     * [
     *     0 => '超级管理员',
     *     1 => '管理员',
     * ]
     */
    protected function getRolesArray()
    {
        $roles = AdminRole::find()->asArray()->all();
        if(!empty($roles) && is_array($roles)){
            $roles = ArrayHelper::map($roles, 'id', 'roleName');
        }
        return $roles;
    }


    public function actionValidate()
    {
        $adminName = $_POST['name'];
        $pass = $_POST['password'];
        $realName = $_POST['realName'];
        if (!preg_match(Validate::$user_name['rule'], $adminName)) {
            echo  Validate::$user_name['msg'];
        }
        if (!preg_match(Validate::$password['rule'], $pass)) {
            echo Validate::$password['msg'];
        }
        if(!preg_match(Validate::$name['rule'],$realName)){
            echo Validate::$name['msg'];
        }
    }

}